<template>
  <div class="img_box">
    <input id="imgFile" type="file" @change="handleFileChange" ref="inputer" accept="image/*" />
    <label for="imgFile" class="label_img"></label>
    <img :src="imgURL" />
  </div>
</template>

<script>
  // import axios from 'axios'
  import {uploadImg} from '@/service/get-data'
  export default {
    name: 'imgUpload',
    props: {
      value: {
        // 绑定默认的value prop
        default: undefined
      }
    },
    data () {
      return {
        file: '', // 文件
        imgURL: require('../../images/person_logo.png')
      }
    },
    methods: {
      async handleFileChange (e) {
        // let inputDom = this.$refs.inputer
        // 获取文件数据
        this.file = e.target.files[0]
        let size = Math.floor(this.file.size / 1024 / 1024)
        // 文件大小
        if (size > 2) {
          this.$message({message: '请选择小于2M的图片'})
          return false
        }

        let formdata = new FormData()
        formdata.append('file', this.file, 'fileName')

        let res = await uploadImg(formdata)
        console.log(res)
      },
      imgPreview (file) {
        let self = this
        let windowURL = window.URL || window.webkitURL
        if (/^image/.test(file.type)) {
          // // 创建一个 reader实例
          // let reader = new FileReader()
          // // 将图片转为 base64格式
          // reader.readAsDataURL(file)
          // // 读取成功后的处理
          // reader.onload = (e) => {
          //   self.urldata = e.target.result
          //   self.imgURL = e.target.result
          // }
          self.imgURL = windowURL.createObjectURL(file)
        }
      },
      async uploadFormData (file) {
        // 创建一个 formdata
        let formdata = new FormData()
        formdata.append('file', file)
        // 请求配置
       // let config = {headers: {'Content-type': 'multipart/form-data'}}
        let res = await uploadImg(file)
        console.log(res)
        // axios.posts('/upload', formdata, config).then((res) => {
        //   console.log(res)
        // })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .img_box {
    position: relative;
    width: 136px;
    height: 136px;
    img{
      width: 100%;
    }
  }
  input{
    position: absolute;
    left: -99999px;
  }
  .label_img{
    position: absolute;
    top: 0;left: 0;right: 0;bottom: 0;
    z-index: 10; /* 这个z-index之后说到*/
  }
</style>